

package com.hlingsoft.kkh.action.v20;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.action.BaseAction;
import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.entity.Result;
import com.hlingsoft.kkh.entity.vo.EventsVo1;
import com.hlingsoft.kkh.entity.vo.StartsVo;
import com.hlingsoft.kkh.util.Common;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户
 *
 * @author Herbert
 */
@Controller
@RequestMapping("/v20/user")
public class UserAction_V20 extends BaseAction {



    private final String defaultHeadImageUrl = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/default.png";

    private final int rows = 10;



    /**
     * 验证码
     *
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/verifyCode.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> verifyCode(
            @RequestParam(value = "phone") String phone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String str = Common.Randoms();
            resultMap.put("result", true);
            try {
                List<String> list = new ArrayList<>();

                VerifyCode verifyCode = verifyCodeDao.getVerifyCodeByPhone(phone);
                Result result = messageService.sendSmsforEvent(phone, str);
                //短信接口请求成功
                if (result.getCode().equals("2")) {
                    //新用户，插入数据表
                    if (verifyCode == null) {
                        VerifyCode verifyCode1 = new VerifyCode();
                        verifyCode1.setPhone(phone);
                        verifyCode1.setCode(str);
                        verifyCode1.setTime(new Date());
                        verifyCodeDao.addVerifyCode(verifyCode1);
                    }
                    //老用户，更新数据表
                    else {
                        verifyCode.setPhone(verifyCode.getPhone());
                        verifyCode.setTime(new Date());
                        verifyCode.setCode(str);
                        verifyCodeDao.updateVerifyCode(verifyCode);
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                    resultMap.put("verifyCode", str);

                }
                //手机号码不对
                else if (result.getCode().equals("406")) {
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
                //其他调用短信接口异常
                else {
                    if (verifyCode != null) {
                        resultMap.put("verifyCode", verifyCode.getCode());
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("msg", "服务暂不可用");
            resultMap.put("result", false);
        }

        return resultMap;

    }



    /**
     * 微信登陆
     *
     * @param name
     * @param gender
     * @param weChatId
     * @param longitude
     * @param latitude
     * @param request
     * @return
     */
    @RequestMapping(value = "/login.json")
    @ResponseBody
    public Map<String, Object> login(
            @RequestParam(value = "name", defaultValue = "0") String name,
            @RequestParam(value = "udId", defaultValue = "0") String udId,
            @RequestParam(value = "headImage", required = false) String headImage,
            @RequestParam(value = "gender", defaultValue = "1") int gender,
            @RequestParam(value = "weChatId", required = false) String weChatId,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "type", defaultValue = "0") int type,  //0.短信登陆 1.微信登陆 2.微博登陆
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (type == 0) {
                AppUser user = userDao.getUserByPhone(phone);
                //新用户登陆
                if (user == null) {
                    user = new AppUser();
                    user.setIsNew(1);
                    user.setPhone(phone);
                    user.setWeChatId(weChatId);
                    if (name.equals("0")) {
                        name = phone;
                        String regex = "****";
                        name = name.replaceAll(name.substring(3, 7), regex);
                    }
                    name = Common.encodeStr(name);
                    user.setName(name);
                    user.setUdId(udId);
                    user.setHeadImage(defaultHeadImageUrl);
                    user.setGender(gender);
                    user.setAddress(address);
                    user.setSignature(signature);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());
                    user.setType(type);
                    userDao.addUser(user);

                    //登入默认关注小飞
                    Focus focus = new Focus();
                    focus.setFansId(user.getId());
                    focus.setAttentionsId(1);
                    focusDao.addFocus(focus);
                } else {
                    user.setUdId(udId);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setUpdateTime(new Date());
                    user.setIsNew(0);
                    userDao.updateUser(user);
                }
                resultMap.put("user", user);
            } else {
                AppUser user = userDao.getUserByWeChatId(weChatId);
                if (user == null) {
                    user = new AppUser();
                    user.setIsNew(1);
                    user.setUdId(udId);
                    user.setPhone(phone);
                    user.setWeChatId(weChatId);
                    user.setName(name);

                    //微信头像传到
                    URL url = new URL(headImage);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    InputStream inStream = conn.getInputStream();
                    byte[] data = Common.readInputStream(inStream);
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    File imageFile = new File(System.currentTimeMillis() + "");
                    FileOutputStream outStream = new FileOutputStream(imageFile);
                    outStream.write(data);
                    outStream.close();

                    InputStream content = new FileInputStream(imageFile);
                    String fileName = imageFile.getName();
                    putObject(dateString, fileName, content, imageFile.length());
                    headImage = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/" + dateString + "/" + fileName;

                    user.setHeadImage(headImage);
                    user.setGender(gender);
                    user.setAddress(address);
                    user.setSignature(signature);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());
                    user.setType(type);
                    userDao.addUser(user);

                    //登入默认关注小飞
                    Focus focus = new Focus();
                    focus.setFansId(user.getId());
                    focus.setAttentionsId(1);
                    focusDao.addFocus(focus);
                } else {
                    user.setIsNew(0);
                    user.setUdId(udId);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setUpdateTime(new Date());
                    userDao.updateUser(user);
                }
                resultMap.put("user", user);
            }

            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }

        return resultMap;

    }

    /**
     * 个人中心头部信息
     * @param myId
     * @param toId
     * @param request
     * @return
     */
    @RequestMapping("/centerHead.json")
    @ResponseBody
    public Map<String, Object> centerHead(
                @RequestParam(value = "myId")  long myId,
                @RequestParam(value = "toId") long toId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(toId);
            long attentionsCount = focusDao.getAttentionsByIdCount(toId);
            if(user!=null){
                user.setAttentionsCount(attentionsCount);
                long fansCount = focusDao.getFansByIdCount(toId);
                user.setFansCount(fansCount);

                long eventsCount = eventsDao.getEventsByAppUserIdCount(toId);
                user.setEventsCount(eventsCount);

                user.setCollectCount(collectDao.getByAppUserIdCount(toId));

                if (focusDao.getFocus(myId,toId)==null){
                    user.setIsFocus(0);
                } else {
                    user.setIsFocus(1);
                    if (focusDao.getFocus(toId,myId)!=null){
                        user.setIsFocus(2);
                    }
                }

                resultMap.put("user", user);
                resultMap.put("result", true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }



    /**
     * 个人中心信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/center.json")
    @ResponseBody
    public Map<String, Object> centre(
            @RequestParam(value = "myId") Integer myId,
            @RequestParam(value = "toId") Integer toId,
            @RequestParam(value = "type",defaultValue = "1",required = false) int type,     //1.主题，2.喜欢，3.关注，4.粉丝
            @RequestParam(value = "pageNum",defaultValue = "1",required = false) int pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<EventsVo1> eventsVo1List = new ArrayList<EventsVo1>();
            switch (type) {
                case 1: {
                    List<Events> eventsList = eventsDao.getEventsByAppUserId(toId,(pageNum-1)*rows,rows);
                    for (Events events : eventsList) {

                        List<AppUser> collectUserList = new ArrayList<AppUser>();

                        EventsVo1 eventsVo1 = new EventsVo1();
                        //活动id
                        eventsVo1.setId(events.getId());
                        //活动名
                        eventsVo1.setName(events.getName());
                        //活动图片
                        EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                        List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                        eventsVo1.setImageList(imageList);
                        eventsVo1.setEventCommentsId(firstEventComments.getId());
                        //活动发布人信息
                        eventsVo1.setAppUserId(events.getAppUserId());
                        eventsVo1.setAppUser(userDao.getUserById(events.getAppUserId()));
                        //活动描述
                        eventsVo1.setDescription(events.getDescription());

                        //评论
                        List<Reply> replyList = replyDao.getReplyByEventCommentsId(firstEventComments.getId(), 0, 2);
                        for (Reply reply:replyList){
                            AppUser my = userDao.getUserById(reply.getMyId());
                            if(my!=null){
                                reply.setMyHeadImage(my.getHeadImage());
                            }
                        }
                        Collections.sort(replyList, new Comparator<Reply>() {
                            @Override
                            public int compare(Reply o1, Reply o2) {
                                return o1.getCreateTime().compareTo(o2.getCreateTime());
                            }
                        });
                        eventsVo1.setReplyList(replyList);

                        //经纬度
                        eventsVo1.setLatitude(events.getLatitude());
                        eventsVo1.setLongitude(events.getLongitude());

                        //创建时间
                        eventsVo1.setCreateAddress(events.getCreateAddress());
                        eventsVo1.setCreateTime(events.getCreateTime());
                        eventsVo1.setUpdateTime(events.getUpdateTime());

                        List<Collect> collectList =  collectDao.getByEventsId(events.getId(),0,10);
                        for (Collect collect:collectList){
                            AppUser appUser = userDao.getUserById(collect.getAppUserId());
                            if (appUser!=null){
                                collectUserList.add(appUser);
                            }
                        }
                        eventsVo1.setCollectUserList(collectUserList);
                        eventsVo1.setCollectCount(collectDao.getByEventsIdCount(events.getId()));

                        //是否能收藏
                        if (myId != 0) {
                            if (collectDao.getByIds(myId,events.getId())==null) {
                                eventsVo1.setIsCollect(0);
                            } else {
                                eventsVo1.setIsCollect(1);
                            }
                        } else {
                            eventsVo1.setIsCollect(0);
                        }



                        eventsVo1List.add(eventsVo1);
                    }
                    resultMap.put("eventsVo1List", eventsVo1List);
                    resultMap.put("result", true);
                    break;
                }

                case 2: {

                    List<Events> eventsList = new ArrayList<Events>();
                    List<Collect> eventsCollectList = collectDao.getByAppUserId(toId,(pageNum-1)*rows,rows);

                    for (Collect collect : eventsCollectList) {
                        eventsList.add(eventsDao.getEventsById(collect.getEventsId()));
                    }

                    for (Events events : eventsList) {

                        List<AppUser> collectUserList = new ArrayList<AppUser>();

                        EventsVo1 eventsVo1 = new EventsVo1();
                        //活动id
                        eventsVo1.setId(events.getId());
                        //活动名
                        eventsVo1.setName(events.getName());
                        //活动图片
                        EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                        List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                        eventsVo1.setImageList(imageList);
                        eventsVo1.setEventCommentsId(firstEventComments.getId());
                        //活动发布人信息
                        eventsVo1.setAppUserId(events.getAppUserId());
                        eventsVo1.setAppUser(userDao.getUserById(events.getAppUserId()));
                        //活动描述
                        eventsVo1.setDescription(events.getDescription());

                        //评论
                        List<Reply> replyList = replyDao.getReplyByEventCommentsId(firstEventComments.getId(), 0, 2);
                        for (Reply reply:replyList){
                            AppUser my = userDao.getUserById(reply.getMyId());
                            if(my!=null){
                                reply.setMyHeadImage(my.getHeadImage());
                            }
                        }
                        Collections.sort(replyList, new Comparator<Reply>() {
                            @Override
                            public int compare(Reply o1, Reply o2) {
                                return o1.getCreateTime().compareTo(o2.getCreateTime());
                            }
                        });
                        eventsVo1.setReplyList(replyList);
                        //经纬度
                        eventsVo1.setLatitude(events.getLatitude());
                        eventsVo1.setLongitude(events.getLongitude());

                        //创建时间
                        eventsVo1.setCreateAddress(events.getCreateAddress());
                        eventsVo1.setCreateTime(events.getCreateTime());
                        eventsVo1.setUpdateTime(events.getUpdateTime());


                        //收藏人
                        List<Collect> collectList =  collectDao.getByEventsId(events.getId(),0,10);
                        for (Collect collect:collectList){
                            AppUser appUser = userDao.getUserById(collect.getAppUserId());
                            if (appUser!=null){
                                collectUserList.add(appUser);
                            }
                        }
                        eventsVo1.setCollectUserList(collectUserList);
                        eventsVo1.setCollectCount(collectDao.getByEventsIdCount(events.getId()));

                        //是否能收藏
                        if (myId != 0) {
                            if (collectDao.getByIds(myId,events.getId())==null) {
                                eventsVo1.setIsCollect(0);
                            } else {
                                eventsVo1.setIsCollect(1);
                            }
                        } else {
                            eventsVo1.setIsCollect(0);
                        }


                        eventsVo1List.add(eventsVo1);
                    }
                    resultMap.put("eventsVo1List", eventsVo1List);
                    resultMap.put("result", true);
                    break;
                }

                case 3: {
                    List<Focus>  attentionsList= focusDao.getAttentionsById(toId,(pageNum-1)*rows,rows);
                    List<StartsVo> startVolist = new ArrayList<StartsVo>();
                    for (Focus focus : attentionsList) {
                        StartsVo startsVo = new StartsVo();
                        AppUser appUser = userDao.getUserById(focus.getAttentionsId());
                        if (appUser!=null){
                            //获取关注人粉丝数
                            long fansCount = focusDao.getFansByIdCount(appUser.getId());
                            appUser.setFansCount(fansCount);

                            //粉丝最新发布的评论
                            Events events = eventsDao.getNewestEventsByUserId(appUser.getId());

                            //判断是否可以关注
                            if (focusDao.getFocus(appUser.getId(), myId) == null) {
                                appUser.setIsFocus(1);
                            } else {
                                appUser.setIsFocus(2);
                            }

                            startsVo.setAppUser(appUser);
                            startsVo.setNewestEvents(events);

                            startVolist.add(startsVo);
                        }
                    }
                    resultMap.put("startVolist",startVolist);
                    resultMap.put("result",true);
                    break;
                }

                case 4: {
                    List<Focus>  fansList= focusDao.getFansById(toId,(pageNum-1)*rows,rows);
                    List<StartsVo> startVolist = new ArrayList<StartsVo>();
                    for (Focus focus : fansList) {

                        //粉丝用户
                        StartsVo startsVo = new StartsVo();

                        //获取关注人
                        AppUser appUser = userDao.getUserById(focus.getFansId());

                        if (appUser!=null){
                            //获取关注人粉丝数
                            long fansCount = focusDao.getFansByIdCount(appUser.getId());
                            appUser.setFansCount(fansCount);

                            //粉丝最新发布的评论
                            Events events = eventsDao.getNewestEventsByUserId(appUser.getId());

                            //判断是否可以关注
                            if (focusDao.getFocus(myId, appUser.getId()) == null) {
                                appUser.setIsFocus(0);
                            } else {
                                appUser.setIsFocus(2);
                            }

                            startsVo.setAppUser(appUser);
                            startsVo.setNewestEvents(events);

                            startVolist.add(startsVo);
                        }
                    }
                    resultMap.put("startVolist",startVolist);
                    resultMap.put("result",true);
                    break;
                }
            }


        } catch (Exception e){
            e.printStackTrace();
            resultMap.put("result", false);
        }

        return resultMap;
    }


    /**
     * 个人资料页面
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("/info.json")
    @ResponseBody
    public Map<String, Object> info(
            @RequestParam(value = "userId") long userId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            List<Profession> professionList = professionDao.getProfession();
            for (Profession profession:professionList){
                if (profession.getId()==user.getProfessionId()){
                    profession.setIsChecked(1);
                }
                else {
                    profession.setIsChecked(0);
                }
            }


            List<Interest> interestList = interestDao.getInterest();
            for (Interest interest:interestList){
                interest.setIsChecked(0);
                List<Integer> interestIdList = Common.strToIntegerList(user.getInterestIds());
                for (Integer interestId:interestIdList){
                      if (interest.getId()==interestId){
                          interest.setIsChecked(1);
                      }
                }
            }

            resultMap.put("user", user);
            resultMap.put("professionList", professionList);
            resultMap.put("interestList", interestList);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 用户编辑
     *
     * @param userId
     * @param name
     * @param gender
     * @param address
     * @param signature
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> edit(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "gender", required = false) Integer gender,
            @RequestParam(value = "professionId",required = false) Integer professionId,
            @RequestParam(value = "interestIds",required = false) String interestIds,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "signature", required = false) String signature,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            MultipartFile files = null;
            if (request instanceof MultipartHttpServletRequest) {
                files = ((MultipartHttpServletRequest) request).getFile("files");
            }

            //上传头像
            if (files != null) {
                String fileName = files.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, files.getInputStream(),
                        files.getSize());
                String headImage = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/" + dateString + "/" + fileName;
                user.setHeadImage(headImage);
            }
            if (name != null) {
                user.setName(name);
            }

            if (gender != null) {
                user.setGender(gender);
            }

            if (professionId != null) {
                user.setProfessionId(professionId);
            }

            if (interestIds!=null) {
                user.setInterestIds(interestIds);
            }

            if (address != null) {
                user.setAddress(address);
            }
            if (signature != null) {
                user.setSignature(signature);
            }
            user.setUpdateTime(new Date());

            userDao.updateUser(user);
            resultMap.put("user", user);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }



    /**
     * 消息中心
     * @param userId
     * @param type
     * @param request
     * @return
     */
    @RequestMapping("/messageCenter.json")
    @ResponseBody
    public Map<String, Object> messageCenter(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "type",defaultValue = "1",required = false)  int type,
            @RequestParam(value = "pageNum",defaultValue = "1",required = false)int pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (type==1){
                List<Chat> chatList = chatDao.getChatList(userId, (pageNum - 1) * rows, rows);
                for (Chat chat:chatList){
                    if (userId==chat.getMyId()&&userId!=chat.getToId()){
                        chat.setType(1);
                    }else{
                        chat.setType(2);
                    }
                }
                messageStatusDao.readChat(userId);
                resultMap.put("chatList",chatList);
                resultMap.put("result",true);
            }else if (type==2){
                List<Notification> notificationList = notificationDao.getNotificationByToId(userId, (pageNum - 1) * rows, rows);
                messageStatusDao.readNotification(userId);
                resultMap.put("notificationList",notificationList);
                resultMap.put("result",true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }




    /**
     * 图片删除
     *
     * @param imageId
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteImage.json")
    @ResponseBody
    public Map<String, Object> deleteImage(
            @RequestParam(value = "imageId") long imageId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            Image imageRecord = imageDao.getImageById(imageId);
            long eventsId = imageRecord.getEventsId();
            long eventCommentsId = imageRecord.getEventCommentsId();


            //判断评论中是否只有张图片，只有一张图片，删除评论

            EventComments firstEventComments = eventCommentsDao.getFirstEventComments(imageRecord.getEventsId());  //获取活动的第一个评论
            EventComments eventComments = eventCommentsDao.getCommentsListById(imageRecord.getEventCommentsId()); //获取图片所在评论


            //判断评论中图片只有一张
            if (imageDao.getImageByEventCommentsIdCount(imageRecord.getEventCommentsId()) == 1) {

                //删除图片
                imageRecord.setAvailable(0);
                imageDao.updateImage(imageRecord);

                //删除图片的分享
                List<Share> shareList = shareDao.getShareByImageId(imageId);
                for (Share share : shareList) {
                    share.setAvailable(0);
                    shareDao.updateShare(share);
                }

                //图片为活动中唯一图片
                if (firstEventComments.getId() == eventComments.getId()) {
                    //删除events
                    Events events = eventsDao.getEventsById(eventsId);
                    events.setAvailable(0);
                    eventsDao.updateEvents(events);

                    //删除评论
                    eventComments.setAvailable(0);
                    eventCommentsDao.updateEventComments(eventComments);

                    //删除点赞
                    List<Likes> likesList = likesDao.getLikesByEventsId(eventsId, 0, 100);
                    for (Likes likes : likesList) {
                        likes.setAvailable(0);
                        likesDao.updateLikes(likes);
                    }

                    //删除分享
                    List<Share> eventShareList = shareDao.getShareByEventsId(eventsId);
                    for (Share share : eventShareList) {
                        share.setAvailable(0);
                        shareDao.updateShare(share);
                    }
                } else {

                    //删除评论
                    eventComments.setAvailable(0);
                    eventCommentsDao.updateEventComments(eventComments);

                    //删除评论点赞
                    List<Likes> likesList = likesDao.getLikesByEventCommentsId(eventCommentsId,0,100);
                    for (Likes likes : likesList) {
                        likes.setAvailable(0);
                        likesDao.updateLikes(likes);
                    }
                }
            } else {
                imageRecord.setAvailable(0);
                imageDao.updateImage(imageRecord);

                //删除图片的分享
                List<Share> shareList = shareDao.getShareByImageId(imageId);
                for (Share share : shareList) {
                    share.setAvailable(0);
                    shareDao.updateShare(share);
                }
            }
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 删除events
     *
     * @param eventsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteEvents.json")
    @ResponseBody
    public Map<String, Object> deleteEvents(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventsId") long eventsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            Events events = eventsDao.getEventsById(eventsId);
            if (userId == events.getAppUserId()) {
                if (events!=null){

                    //删除相关帖子
                    List<EventComments> eventCommentsList =  eventCommentsDao.getCommentsListByEventIdWithNone(eventsId);
                    for (EventComments eventComments:eventCommentsList){
                        eventComments.setAvailable(0);
                        eventCommentsDao.updateEventComments(eventComments);
                    }

                    //删除相关图片
                    List<Image>  imageList=imageDao.getImageByEventsIdWithNone(eventsId);
                    for (Image image:imageList){
                        image.setAvailable(0);
                        imageDao.updateImage(image);
                    }


                    //删除相关点赞
                    List<Likes> likesList = likesDao.getLikesByEventsIdWithNone(eventsId);
                    for (Likes likes:likesList){
                        likes.setAvailable(0);
                        likesDao.updateLikes(likes);
                    }

                    //删除相关消息
                    List<Notification> notificationList = notificationDao.getNotificationByEventsIdWithNone(eventsId);
                    for (Notification notification : notificationList) {
                        notification.setAvailable(0);
                        notificationDao.updateNotification(notification);
                    }

                    //删除举报
                    List<Report> reportList = reportDao.getReportByEventsIdWithNone(eventsId);
                    for (Report report : reportList) {
                        report.setAvailable(0);
                        reportDao.updateReport(report);
                    }

                    //删除分享
                    List<Share> shareList = shareDao.getShareByEventsId(eventsId);
                    for (Share share:shareList){
                        share.setAvailable(0);
                        shareDao.updateShare(share);
                    }

                    //删除社区
                    events.setAvailable(0);
                    eventsDao.updateEvents(events);

                    resultMap.put("result",true);
                }
            } else {
                resultMap.put("msg", "只有活动创建者才能删除该活动");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }




    /**
     * 退出登录
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("/logout.json")
    @ResponseBody
    public Map<String, Object> logout(
            @RequestParam(value = "userId") long userId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            userDao.updateUdIdById(userId);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");


        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "headImg/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }





}
